<?php

namespace app\controller\admin\lineup;

use app\model\admin\lineup\LineupTeam;
use app\model\admin\lineup\LineupTeamContent;
use app\model\admin\lineup\LineupTeamLabel;
use laytp\controller\Backend;
use think\facade\Db;

/**
 * Class Career
 * @package app\controller\admin\ah
 */
class Team extends Backend
{
    protected $model;
    protected $noNeedAuth = ['index', 'info', 'style'];
    protected $type = 1;

    public function initialize()
    {
        $this->model = new LineupTeam();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 列表
     *  all_data参数的值为true时，表示查询表中所有数据集，否则进行分页查询
     * @return mixed
     */
    public function index()
    {
        $where = $this->buildSearchParams();
        $order = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->where("audit_status", 2)->order($order)->cache(true)->select()->toArray();
        } else {
            $limit = $this->request->param('limit', 10);
            //审核通过的
            $data = $this->model->with('style')->withCount("collect")
                ->field("*,like_number+basic_like_number as total_number,basic_power_number+game_power_number as total_power")
                ->where($where)->where("audit_status", 2)
                ->order($order)->paginate($limit)->toArray();
            foreach ($data['data'] as &$item) {
            }
        }
        return $this->success('数据获取成功', $data);
    }

    public function style()
    {
        //获取游戏的样式
        $gameId = $this->request->param('game_id');
        $style = Db::name("lineup_style")->where("lineup_game_id", $gameId)->where("status", 1)->find();
        if (!$style) {
            return $this->error("不存在可用样式");
        }
        if (is_object($style)) {
            $style = $style->toArray();
        }
        $styleRelationIds = Db::name("lineup_style_label_relation")->where("lineup_style_id", $style['id'])->select()->toArray();
        $styleRelations = [];
        foreach ($styleRelationIds as $item) {
            $styleRelations[$item['type']][] = $item['label_id'];
        }
        $info = [];
        $info['style'] = $style;
        $info['styleRelations'] = $styleRelations;
        return $this->success('数据获取成功', $info);
    }

    //添加
    public function add()
    {
        if (!$this->request->param("game_id")) {
            return $this->error("缺少游戏id");
        }
        $gameId = $this->request->param('game_id');
        $style = Db::name("lineup_style")->where("lineup_game_id", $gameId)->where("status", 1)->find();
        if (!$style) {
            return $this->error("不存在可用样式");
        }
        $post = $this->request->post();
        $data = [
            'team_name' => $post['team_name'],
            'team_description' => $post['team_description'],
            'audit_status' => 2,
            'lineup_style_id' => $style['id'],
            'lineup_game_id' => $gameId,
            'game_power_number' => $style['start_power_number'],
            'basic_like_number' => $post['basic_like_number'],
            'basic_collect_number' => $post['basic_collect_number'],
            'basic_power_number' => $post['basic_power_number'],
            'create_time' => date("Y-m-d H:i:s"),
            'update_time' => date("Y-m-d H:i:s")
        ];
        if (isset($post['author_name'])) $data['author_name'] = $post['author_name'];
        if (isset($post['author_avatar'])) $data['author_avatar'] = $post['author_avatar'];
        try {
            Db::startTrans();
            $id = $this->model->insertGetId($data);
            if ($id) {
                //先处理标签
                if (isset($post['team_labels'])) {
                    $teamLabels = explode(",", $post['team_labels']);
                    $insertLabels = [];
                    foreach ($teamLabels as $item) {
                        $insertLabels[] = [
                            'lineup_game_id' => $gameId,
                            'lineup_team_id' => $id,
                            'label_id' => $item,
                        ];
                    }
                    if (count($insertLabels) > 0) {
                        (new LineupTeamLabel())->insertAll($insertLabels);
                    }
                }
                $insertContents = [];
                //处理阵容1 优先查看图鉴 -》 关联图鉴 -》 关联标签
                if (isset($post['guide_id']) && !empty($post['guide_id'])) {
                    $guideIds =  $post['guide_id'];
                    $contentIds = [];
                    $guideLabels = [];
                    $masterGuideLabel = [];
                    if (isset($post['master_guide_label'])) $masterGuideLabel = $post['master_guide_label'];
                    if (isset($post['content_id'])) $contentIds = $post['content_id'];
                    if (isset($post['guide_label'])) $guideLabels =$post['guide_label'];
                    foreach ($guideIds as $key => $item) {
                        if (empty($item)) {
                            continue;
                        }
                        $new = [
                            'lineup_game_id' => $gameId,
                            'lineup_team_id' => $id,
                            'guide_id' => $item,
                            'type' => 1,
                            'create_time' => date("Y-m-d H:i:s"),
                            'update_time' => date("Y-m-d H:i:s")
                        ];
                        if (isset($masterGuideLabel[$key]) && !empty($masterGuideLabel[$key])) {
                            $new['label_id'] = $masterGuideLabel[$key];
                        }
                        if (isset($contentIds[$key]) && !empty($contentIds[$key])) {
                            $new['collocation_content'] = json_encode(explode(",", $contentIds[$key]));
                        }
                        if (isset($guideLabels[$key]) && !empty($guideLabels[$key])) {
                            $new['collocation_label'] = json_encode(explode(",", $guideLabels[$key]));
                        }
                        $insertContents[] = $new;
                    }
                }
                //处理阵容2 优先查看图鉴 -》 关联图鉴 -》 关联标签
                if (isset($post['guide_id2']) && !empty($post['guide_id2'])) {
                    $guideIds = $post['guide_id2'];
                    $contentIds = [];
                    $guideLabels = [];
                    $masterGuideLabel = [];
                    if (isset($post['master_guide_label2'])) $masterGuideLabel = $post['master_guide_label2'];
                    if (isset($post['content_id2'])) $contentIds =$post['content_id2'];
                    if (isset($post['guide_label2'])) $guideLabels = $post['guide_label2'];
                    foreach ($guideIds as $key => $item) {
                        if (empty($item)) {
                            continue;
                        }
                        $new = [
                            'lineup_game_id' => $gameId,
                            'lineup_team_id' => $id,
                            'guide_id' => $item,
                            'type' => 2,
                            'create_time' => date("Y-m-d H:i:s"),
                            'update_time' => date("Y-m-d H:i:s")
                        ];
                        if (isset($masterGuideLabel[$key]) && !empty($masterGuideLabel[$key])) {
                            $new['label_id'] = $masterGuideLabel[$key];
                        }
                        if (isset($contentIds[$key]) && !empty($contentIds[$key])) {
                            $new['collocation_content'] = json_encode(explode(",", $contentIds[$key]));
                        }
                        if (isset($guideLabels[$key]) && !empty($guideLabels[$key])) {
                            $new['collocation_label'] = json_encode(explode(",", $guideLabels[$key]));
                        }
                        $insertContents[] = $new;
                    }
                }
                if (count($insertContents) > 0) {
                    (new LineupTeamContent())->insertAll($insertContents);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('添加成功', $post);
            } else {
                Db::rollback();
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }


    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (!$info) {
            return $this->error('ID参数错误');
        }
        $style = Db::name("lineup_style")->where("lineup_game_id", $info->lineup_game_id)->where("status", 1)->value("id");
        if (!$style) {
            return $this->error("不存在可用样式");
        }
        $post = $this->request->post();

        if (isset($post->icon) && !empty($post->icon)) {
            $post->icon = getRelativeUrl($post->icon);
        }
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        $info->lineup_style_id =$style;
        try {
            Db::startTrans();
            $updateRes = $info->save();
            if ($updateRes) {
                $teamLabelModel = new LineupTeamLabel();
                $teamContentModel = new LineupTeamContent();
                $teamLabelModel->where("lineup_team_id",$id)->delete();
                $teamContentModel->where("lineup_team_id",$id)->delete();
                $gameId = $info->lineup_game_id;
                //先处理标签
                if (isset($post['team_labels'])) {
                    $teamLabels = explode(",", $post['team_labels']);
                    $insertLabels = [];
                    foreach ($teamLabels as $item) {
                        $insertLabels[] = [
                            'lineup_game_id' => $gameId,
                            'lineup_team_id' => $id,
                            'label_id' => $item,
                        ];
                    }
                    if (count($insertLabels) > 0) {
                        $teamLabelModel->insertAll($insertLabels);
                    }
                }

                $insertContents = [];
                //处理阵容1 优先查看图鉴 -》 关联图鉴 -》 关联标签
                if (isset($post['guide_id']) && !empty($post['guide_id'])) {
                    $guideIds = $post['guide_id'];
                    $contentIds = [];
                    $guideLabels = [];
                    $masterGuideLabel = [];
                    if (isset($post['master_guide_label'])) $masterGuideLabel = $post['master_guide_label'];
                    if (isset($post['content_id'])) $contentIds = $post['content_id'];
                    if (isset($post['guide_label'])) $guideLabels =$post['guide_label'];
                    foreach ($guideIds as $key => $item) {
                        if (empty($item)) {
                            continue;
                        }
                        $new = [
                            'lineup_game_id' => $gameId,
                            'lineup_team_id' => $id,
                            'guide_id' => $item,
                            'type' => 1,
                            'create_time' => date("Y-m-d H:i:s"),
                            'update_time' => date("Y-m-d H:i:s")
                        ];
                        if (isset($masterGuideLabel[$key]) && !empty($masterGuideLabel[$key])) {
                            $new['label_id'] = $masterGuideLabel[$key];
                        }
                        if (isset($contentIds[$key]) && !empty($contentIds[$key])) {
                            $new['collocation_content'] = json_encode(explode(",", $contentIds[$key]));
                        }
                        if (isset($guideLabels[$key]) && !empty($guideLabels[$key])) {
                            $new['collocation_label'] = json_encode(explode(",", $guideLabels[$key]));
                        }
                        $insertContents[] = $new;
                    }
                }
                //处理阵容2 优先查看图鉴 -》 关联图鉴 -》 关联标签
                if (isset($post['guide_id2']) && !empty($post['guide_id2'])) {
                    $guideIds =$post['guide_id2'];
                    $contentIds = [];
                    $guideLabels = [];
                    $masterGuideLabel = [];
                    if (isset($post['master_guide_label2'])) $masterGuideLabel =$post['master_guide_label2'];
                    if (isset($post['content_id2'])) $contentIds = $post['content_id2'];
                    if (isset($post['guide_label2'])) $guideLabels = $post['guide_label2'];
                    foreach ($guideIds as $key => $item) {
                        if (empty($item)) {
                            continue;
                        }
                        $new = [
                            'lineup_game_id' => $gameId,
                            'lineup_team_id' => $id,
                            'guide_id' => $item,
                            'type' => 2,
                            'create_time' => date("Y-m-d H:i:s"),
                            'update_time' => date("Y-m-d H:i:s")
                        ];
                        if (isset($masterGuideLabel[$key]) && !empty($masterGuideLabel[$key])) {
                            $new['label_id'] = $masterGuideLabel[$key];
                        }
                        if (isset($contentIds[$key]) && !empty($contentIds[$key])) {
                            $new['collocation_content'] = json_encode(explode(",", $contentIds[$key]));
                        }
                        if (isset($guideLabels[$key]) && !empty($guideLabels[$key])) {
                            $new['collocation_label'] = json_encode(explode(",", $guideLabels[$key]));
                        }
                        $insertContents[] = $new;
                    }
                }
                if (count($insertContents) > 0) {
                    $teamContentModel->insertAll($insertContents);
                }
                Db::commit();
                $this->clearCache();
                return $this->success('编辑成功');
            } else {
                Db::rollback();

                return $this->error('编辑失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    public function info()
    {
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        if (is_object($info)) $info = $info->toArray();
        //获取游戏的样式
        $style = Db::name("lineup_style")->where("lineup_game_id", $info['lineup_game_id'])->where("status", 1)->find();
        if (!$style) {
            return $this->error("不存在可用样式");
        }
        if (is_object($style)) {
            $style = $style->toArray();
        }
        $styleRelationIds = Db::name("lineup_style_label_relation")->where("lineup_style_id", $style['id'])->select()->toArray();
        $styleRelations = [];
        foreach ($styleRelationIds as $item) {
            $styleRelations[$item['type']][] = $item['label_id'];
        }
        $info['style'] = $style;
        $info['styleRelations'] = $styleRelations;
        $labels  = (new LineupTeamLabel())->where("lineup_team_id", $id)->column("label_id");
        $info['team_labels'] = implode(",",$labels);
        $contents = (new LineupTeamContent())->where("lineup_team_id",$id)->select()->toArray();
        $info['content_id'] = [];
        $info['master_guide_label'] = [];
        $info['guide_id'] = [];
        $info['guide_label'] = [];
        $info['content_id2'] = [];
        $info['master_guide_label2'] = [];
        $info['guide_id2'] = [];
        $info['guide_label2'] = [];
        foreach ($contents as $item){
            switch ($item['type']){
                case 1:
                    if(!empty($item['label_id'])){
                        $info['master_guide_label'][]= $item['label_id'];
                    }
                    if(!empty($item['guide_id'])){
                        $info['guide_id'][]= $item['guide_id'];
                    }
                    if(!empty($item['collocation_content'])){
                        $info['content_id'][]= implode(",",json_decode($item['collocation_content'],true));
                    }
                    if(!empty($item['collocation_label'])){
                        $info['guide_label'][]= implode(",",json_decode($item['collocation_label'],true));
                    }
                    break;
                case 2:
                    if(!empty($item['label_id'])){
                        $info['master_guide_label2'][]= $item['label_id'];
                    }
                    if(!empty($item['guide_id'])){
                        $info['guide_id2'][]= $item['guide_id'];
                    }
                    if(!empty($item['collocation_content'])){
                        $info['content_id2'][]= implode(",",json_decode($item['collocation_content'],true));
                    }
                    if(!empty($item['collocation_label'])){
                        $info['guide_label2'][]= implode(",",json_decode($item['collocation_label'],true));
                    }
                    break;
            }
        }
        return $this->success('获取成功', $info);
    }

}